package com.wxapp.dispatch.service.job;

import com.wxapp.common.base.util.bean.SpringUtils;
import com.wxapp.common.base.util.jackson.JacksonUtil;
import com.wxapp.common.constant.constant.MqConstant;
import com.wxapp.common.constant.enums.SysNameEnum;
import com.wxapp.common.constant.pojo.vm.ResultVm;
import com.wxapp.common.constant.pojo.vo.FeignRequestVo;
import com.wxapp.common.core.filter.except.ThrowMyException;
import com.wxapp.common.util.check.CheckUtil;
import com.wxapp.common.util.feign.DynamicFeignUtil;
import com.wxapp.common.util.redisson.RedissonUtil;
import com.wxapp.dispatch.api.enums.DispatchRunStatusEnum;
import com.wxapp.dispatch.api.pojo.po.vm.PLoginVm;
import com.wxapp.dispatch.api.pojo.vo.dispatch.QDispatchVo;
import com.wxapp.dispatch.api.pojo.vo.dispatchlogs.QDispatchLogAddVo;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.util.Map;

/**
 * @author lgl
 */
public abstract class BaseJob extends QuartzJobBean {
    private static final Logger log = LoggerFactory.getLogger(BaseJob.class);

    @Override
    protected void executeInternal(JobExecutionContext context) {
        var startTime = System.currentTimeMillis();
        if (!RedissonUtil.tryLock(context.getJobDetail().getKey().toString())) {
            log.error("*****************调度任务" + context.getJobDetail().getKey().toString() + "正在执行*********************");
            return;
        }
        log.info("**********执行定时任务调用开始******************");
        boolean error = false;
        String result = "";
        try {
             var jobDataMap = context.getMergedJobDataMap();
            //获取请求参数
            var dispatchVm = JacksonUtil.parseObject(jobDataMap, QDispatchVo.class);
            //获取token
            if (CheckUtil.isNotNullString(dispatchVm.getLoginName())) {
                String token = "";
                var dynamicClientService= SpringUtils.getBean(DynamicFeignUtil.class);
                ResultVm<PLoginVm> resultVm = JacksonUtil.parseObject(dynamicClientService.executeApi(new FeignRequestVo<Map>(SysNameEnum.ADMIN, "/login", null, Map.of("loginName", dispatchVm.getLoginName(),"type","INSIDER_USER"), HttpMethod.POST)), ResultVm.class);
                if (resultVm.getData() != null) {
                    token = resultVm.getData().getToken();
                }
                dispatchVm.setToken(token);
                log.info("登录获取的token:" + token);
            }
             var dealJob = toDealJob(context, dispatchVm);
            log.info("**********执行结果：" + result + "******************");
            if (dealJob.getCode() !=200){
                error=true;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            result = e.getMessage();
        } finally {
            RedissonUtil.unLock(context.getJobDetail().getKey().toString());
            var runTime = System.currentTimeMillis() - startTime;
            saveDispatch(new QDispatchLogAddVo(context.getJobDetail().getKey().getName(), runTime, error ? DispatchRunStatusEnum.SUCCESS : DispatchRunStatusEnum.FAIL, result));
            log.info("**********执行定时任务" + context.getJobDetail().getKey().toString() + "结束******************");
            log.info("************************执行时间：" + runTime + "ms ******************************");
        }
    }
    @Async
    public void saveDispatch(QDispatchLogAddVo dispatchVm){
        SpringUtils.getBean(RocketMQTemplate.class).syncSend(MqConstant.DISPATCH_JOB,dispatchVm);
    }
    protected abstract ResultVm<Object>  toDealJob(JobExecutionContext context, QDispatchVo dispatchVm);
}
